package com.ywl.designpattern.singleton.type4;

/**
 * @author yuwl
 * @description 单例设计模式-懒汉式（线程安全，同步方法，可用效率低）
 * @since 2024-02-29 09:56
 */
public class Singleton {

    private static Singleton singleton;

    private Singleton() {}

    /**
     * 懒汉式（线程安全，同步方法）
     * @return
     */
    public static synchronized Singleton getInstance() {
        if (singleton == null) {
            singleton = new Singleton();
        }
        return singleton;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                Singleton instance = Singleton.getInstance();
                System.out.println(Thread.currentThread().getName() + ", instance = " + instance);
                System.out.println(Thread.currentThread().getName() + ", instance.hashCode() = " + instance.hashCode());
            }).start();
        }
    }
}
